package com.htfyun;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Debug;
import android.provider.MediaStore;

import com.htfyun.utils.DebugLog;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by sst on 2017/11/27.
 */

public enum  ScanLocalBookManager {
    INSTANCE;


    private List<IScanOverListener> overListenerList = new CopyOnWriteArrayList<>();

    private MyLoader myLoader;

    public void addOverListener(IScanOverListener listener) {

        if (!overListenerList.contains(listener)) {
            overListenerList.add(listener);
        }
    }

    public void removeOverListener(IScanOverListener listener) {
        overListenerList.remove(listener);
    }

    public void init(Activity activity) {
        myLoader = new MyLoader(activity, this);
    }

    public boolean isScanOver() {
        if (myLoader == null) {
            return false;
        }

        return myLoader.isScanOver();
        
    }
    public List<String> getBooksPath() {
        if (myLoader == null) {
            return Collections.emptyList();
        }

        return myLoader.getBooksPath();
    }
    
    
    private static class MyLoader implements LoaderManager.LoaderCallbacks<Cursor> {

        private final static String[] PROJECTION = new String[]{MediaStore.Files.FileColumns._ID,
                MediaStore.Files.FileColumns.DATA,
                MediaStore.Files.FileColumns.SIZE

        };

        private static final String SUFFIX_TXT = ".txt";
        private static final String SUFFIX_PDF = ".pdf";
        private static final String SUFFIX_EPUB = ".epub";
        private static final String SUFFIX_ZIP = ".zip";
        private static final String SUFFIX_CHM = ".chm";
        
        
        private final Activity activity;

        private final WeakReference<ScanLocalBookManager> scanLocalBookManagerWeakReference;

        private List<String> booksPath;

        private AtomicBoolean isScanOver = new AtomicBoolean();
        

        public MyLoader(Activity context, ScanLocalBookManager manager) {
            this.activity = context;
            booksPath = new ArrayList<>();

            this.activity.getLoaderManager().initLoader(0, null, this);

            scanLocalBookManagerWeakReference = new WeakReference<ScanLocalBookManager>(manager);
            
        }

        public boolean isScanOver() {
            return isScanOver.get();
        }

        public void setScanOver(boolean scanOver) {
            isScanOver.set(scanOver);
        }

        public List<String> getBooksPath() {
            return booksPath;
        }
        @Override
        public Loader<Cursor> onCreateLoader(int id, Bundle args) {

            setScanOver(false);
            return new CursorLoader(activity, Uri.parse("content://media/external/file"),
                    PROJECTION, 
                    " (" + MediaStore.Files.FileColumns.DATA + " like ? or "
                    + MediaStore.Files.FileColumns.DATA + " like ? or "
                    + MediaStore.Files.FileColumns.DATA + " like ? or "
                    + MediaStore.Files.FileColumns.DATA + " like ? )"
                    + " and " + MediaStore.Files.FileColumns.SIZE + " > 0",
                    new String[]{
                            "%" + SUFFIX_TXT,
                            "%" + SUFFIX_PDF,
                            "%" + SUFFIX_EPUB,
                            "%" + SUFFIX_CHM}, MediaStore.Files.FileColumns.SIZE + " desc");
        }

        @Override
        public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {

            if (cursor != null && cursor.moveToFirst()) {
                int idindex = cursor.getColumnIndex(MediaStore.Files.FileColumns._ID);
                int dataindex = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
                int sizeindex = cursor.getColumnIndex(MediaStore.Files.FileColumns.SIZE);

                do {
                    String path = cursor.getString(dataindex);

                    booksPath.add(path);
                } while (cursor.moveToNext());

                cursor.close();
            }

            setScanOver(true);
            ScanLocalBookManager manager = scanLocalBookManagerWeakReference.get();
            if (manager != null) {
                
                for (IScanOverListener l : manager.overListenerList
                        ) {

                    l.onOver();
                }
            }
        }

        @Override
        public void onLoaderReset(Loader<Cursor> loader) {

            booksPath.clear();

            setScanOver(false);

            ScanLocalBookManager manager = scanLocalBookManagerWeakReference.get();
            if (manager != null) {

                for (IScanOverListener l : manager.overListenerList
                        ) {

                    l.onOver();
                }
            }
        }
    }
    


}
